package com.auth.manager.security.service;

import cn.hutool.core.util.StrUtil;
import com.auth.manager.pojo.sys.SysRole;
import com.auth.manager.pojo.sys.UserInfo;
import com.auth.manager.service.sys.SysRoleService;
import com.auth.manager.service.sys.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @version 1.0.0
 * @Date: 2022/4/26 20:32
 * @Author ZhuYouBin
 * @Description 自定义用户认证逻辑
 */
@Component // 添加到IOC容器里面
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SysRoleService sysRoleService;

    // 根据用户名称查询数据库信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO 在这个类里面查询数据库信息
        username = StrUtil.trim(username);
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("account_no", username);
        wrapper.last("limit 1");
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (Objects.isNull(userInfo)) {
            throw new UsernameNotFoundException("当前用户不存在");
        }

        List<String> roleLists = new ArrayList<>();
        // 查询用户的角色
        List<SysRole> sysRoleList = sysRoleService.queryUserRole(String.valueOf(userInfo.getUid()));
        if (!CollectionUtils.isEmpty(sysRoleList)) {
            sysRoleList.forEach(sysRole -> {
                roleLists.add(sysRole.getRoleKey());
            });
        }

        return new UserAccount(username, userInfo.getPassword(), roleLists, userInfo);
    }
}
